package au.edu.thinkinghead.synapse;

public class StringSynapse extends CharSynapse {

  public boolean CreateFromString(String a_pShareName, String a_pStringIn) {
    byte[] bs = new byte[a_pStringIn.length()+1];
    System.arraycopy(a_pStringIn.getBytes(), 0, bs, 0, a_pStringIn.length());
    bs[a_pStringIn.length()] = 0;
    return CreateFromArray(a_pShareName, bs.length, bs);
  }
  
  public boolean WriteStringNow(String s) {
    int size;
    if (Size() > s.length()) {
      size = s.length();
    } else {
      size = Size() - 1;
    }
    byte[] bs = new byte[size+1];
    System.arraycopy(s.getBytes(), 0, bs, 0, size);
    bs[size] = 0;
    return WriteArrayNow(bs, bs.length);
  }

  public String ReadStringNow() {
    byte[] rb = new byte[(int)Size()];
    ReadArrayNow(rb);
    for (int i = 0; i < Size(); i++)
    {
       if (rb[i] == 0)
       {
          char[] c = new char[i];
          for (int j = i - 1; j >= 0; j--)
          {
             c[j] = (char)rb[j];
          }
          return new String(c);
       }
    }
    return "";
  }
  
  public void WriteString(String s) {
    int size;
    if (Size() > s.length()) {
      size = s.length();
    } else {
      size = Size() - 1;
    }
    byte[] bs = new byte[size+1];
    System.arraycopy(s.getBytes(), 0, bs, 0, size);
    bs[size] = 0;
    WriteArray(bs, bs.length);   
  }
  
  public void ProtectWriteString(String s) {
    int size;
    if (Size() > s.length()) {
      size = s.length();
    } else {
      size = Size() - 1;
    }
    byte[] bs = new byte[size+1];
    System.arraycopy(s.getBytes(), 0, bs, 0, size);
    bs[size] = 0;
    ProtectWriteArray(bs, bs.length);   
  }

  public String ReadString() {
    byte[] rb = new byte[(int)Size()];
    ReadArray(rb);
    for (int i = 0; i < Size(); i++)
    {
       if (rb[i] == 0)
       {
          char[] c = new char[i];
          for (int j = i - 1; j >= 0; j--)
          {
             c[j] = (char)rb[j];
          }
          return new String(c);
       }
    }
    return "";
  }
  
  public void WriteStringWhenOld(String s) {
    int size;
    if (Size() > s.length()) {
      size = s.length();
    } else {
      size = Size() - 1;
    }
    byte[] bs = new byte[size+1];
    System.arraycopy(s.getBytes(), 0, bs, 0, size);
    bs[size] = 0;
    WriteArrayWhenOld(bs, bs.length);   
  }

  public String ReadStringWhenNew() {
    byte[] rb = new byte[(int)Size()];
    ReadArrayWhenNew(rb);
    for (int i = 0; i < Size(); i++)
    {
       if (rb[i] == 0)
       {
          char[] c = new char[i];
          for (int j = i - 1; j >= 0; j--)
          {
             c[j] = (char)rb[j];
          }
          return new String(c);
       }
    }
    return "";
  }
  
}